package com.qf.servlet;

import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * --- 缘分让我们相遇乱世以外 ---
 *
 * @author SJY
 * @date 2024/11/8
 * @desc
 */
@WebServlet("/user/list")
public class ListServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 已经解决,从请求域取出即可
        // User user = (User) req.getAttribute("user");

        // 换成使用session
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        // 展现全部数据,再查询全部数据
        ArrayList<User> userList = userService.findAll();

        //设置编码格式防止出现乱码
        // resp.setContentType("text/html;charset=utf-8");

        PrintWriter out = resp.getWriter();

        //向外展示数据
        out.write("<html>");
        out.write("<head>");
        out.write("<title>主页</title>");
        out.write("</head>");
        out.write("<body>");
        out.write("<h1>登录成功,欢迎" + user.getUsername( ) + "</h1>");

        out.write("<hr>");
        out.write("<button>");
        out.write("<a href='/logout'>退出</a>");
        out.write("</button>");
        out.write("<hr>");
        out.write("<h2>展现全部数据</h2>");
        out.write("<table border='2'>");
        out.write("<tr>");
        out.write(" <td>编号</td>");
        out.write(" <td>用户名</td>");
        out.write(" <td>密码</td>");
        out.write(" <td>性别</td>");
        out.write(" <td>时间</td>");
        out.write(" <td>手机号</td>");
        out.write("</tr>");
        for (User u : userList) {
            out.write("<tr>");
            out.write(" <td>" + u.getId( ) + "</td>");
            out.write(" <td>" + u.getUsername( ) + "</td>");
            out.write(" <td>" + u.getPassword( ) + "</td>");
            out.write(" <td>" + (u.getSex( ) == 1 ? "男" : "女") + "</td>");
            out.write(" <td>" + u.getCreateTime( ) + "</td>");
            out.write(" <td>" + u.getPhone( ) + "</td>");
            out.write("</tr>");
        }
        out.write("");
        out.write("</table>");
        out.write("</body>");
        out.write("</html>");
    }
}
